/*
 * @(#)AuditLoginOutDAObject.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.framework.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.bean.AuditLoginOut;

/**
  AuditLoginOutDAObject.java

  This class is a DAO for auditLoginOut.

    @author          Scott Tong
    @company         DCIVision Limited
    @creation date   15/07/2003
    @version         $Revision: 1.15.24.1 $
*/

public class AuditLoginOutDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.15.24.1 $";

  public static final String TABLE_NAME = "AUDIT_LOGIN_OUT";

  public AuditLoginOutDAObject(SessionContainer sessionCtn, Connection dbConn) {
    super(sessionCtn, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("USER_RECORD_ID");
    this.vecDBColumn.add("LOGIN_DATETIME");
    this.vecDBColumn.add("LOGIN_STATUS");
    this.vecDBColumn.add("LOGOUT_DATETIME");
    this.vecDBColumn.add("TIMEOUT_FLAG");
    this.vecDBColumn.add("IP_ADDRESS");
    this.vecDBColumn.add("SESSION_ID");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT USER_RECORD_ID, LOGIN_DATETIME, LOGIN_STATUS, LOGOUT_DATETIME, TIMEOUT_FLAG, IP_ADDRESS, SESSION_ID ");
        sqlStat.append("FROM   AUDIT_LOGIN_OUT ");
        sqlStat.append("WHERE  USER_RECORD_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        rs = preStat.executeQuery();
        if (rs.next()) {
          AuditLoginOut tmpAuditLoginOut = new AuditLoginOut();
          tmpAuditLoginOut.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
          tmpAuditLoginOut.setLoginDatetime(getResultSetTimestamp(rs, "LOGIN_DATETIME"));
          tmpAuditLoginOut.setLoginStatus(getResultSetString(rs, "LOGIN_STATUS"));
          tmpAuditLoginOut.setLogoutDatetime(getResultSetTimestamp(rs, "LOGOUT_DATETIME"));
          tmpAuditLoginOut.setTimeoutFlag(getResultSetString(rs, "TIMEOUT_FLAG"));
          tmpAuditLoginOut.setIPAddress(getResultSetString(rs,"IP_ADDRESS"));
          tmpAuditLoginOut.setSessionID(getResultSetString(rs,"SESSION_ID"));
          return(tmpAuditLoginOut);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    AuditLoginOut tmpAuditLoginOut = (AuditLoginOut)((AuditLoginOut)obj).clone();
    synchronized(dbConn) {
      try {
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   AUDIT_LOGIN_OUT(USER_RECORD_ID, LOGIN_DATETIME, LOGIN_STATUS, LOGOUT_DATETIME, TIMEOUT_FLAG, IP_ADDRESS, SESSION_ID) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpAuditLoginOut.getUserRecordID());
        setPrepareStatement(preStat, 2, tmpAuditLoginOut.getLoginDatetime());
        setPrepareStatement(preStat, 3, tmpAuditLoginOut.getLoginStatus());
        setPrepareStatement(preStat, 4, tmpAuditLoginOut.getLogoutDatetime());
        setPrepareStatement(preStat, 5, tmpAuditLoginOut.getTimeoutFlag());
        setPrepareStatement(preStat, 6, tmpAuditLoginOut.getIPAddress());
        setPrepareStatement(preStat, 7, tmpAuditLoginOut.getSessionID());
        preStat.executeUpdate();
        return(tmpAuditLoginOut);
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException("common.E00010", e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    AuditLoginOut auditLoginOut = (AuditLoginOut)((AuditLoginOut)obj).clone();
    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE AUDIT_LOGIN_OUT ");
        sqlStat.append("SET ");
        if(auditLoginOut.getLoginStatus()!=null){
          sqlStat.append("LOGIN_STATUS=?,");
        }
        if(auditLoginOut.getLogoutDatetime()!=null){
          sqlStat.append("LOGOUT_DATETIME=?,");
        }
        if(auditLoginOut.getTimeoutFlag()!=null){
          sqlStat.append("TIMEOUT_FLAG=?,");
        }
        sqlStat.deleteCharAt(sqlStat.length()-1);

        sqlStat.append("WHERE SESSION_ID=? AND USER_RECORD_ID=? AND LOGIN_DATETIME=?");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        int i=1;
        if(auditLoginOut.getLoginStatus()!=null){
          setPrepareStatement(preStat, i++, auditLoginOut.getLoginStatus());
        }

        if(auditLoginOut.getLogoutDatetime()!=null){
          setPrepareStatement(preStat, i++, auditLoginOut.getLogoutDatetime());
        }

        if(auditLoginOut.getTimeoutFlag()!=null){
          setPrepareStatement(preStat, i++, auditLoginOut.getTimeoutFlag());
        }
        setPrepareStatement(preStat, i++, auditLoginOut.getSessionID());
        setPrepareStatement(preStat, i++, auditLoginOut.getUserRecordID());
        setPrepareStatement(preStat, i++, auditLoginOut.getLoginDatetime());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException("common.E00005");
        } else {
          return(auditLoginOut);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException("common.E00011", e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public synchronized AbstractBaseObject updateBySessionID(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    AuditLoginOut auditLoginOut = (AuditLoginOut)((AuditLoginOut)obj).clone();
    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE AUDIT_LOGIN_OUT ");
        sqlStat.append("SET ");
        if(auditLoginOut.getLoginStatus()!=null){
          sqlStat.append("LOGIN_STATUS=?,");
        }
        if(auditLoginOut.getLogoutDatetime()!=null){
          sqlStat.append("LOGOUT_DATETIME=?,");
        }
        if(auditLoginOut.getTimeoutFlag()!=null){
          sqlStat.append("TIMEOUT_FLAG=?,");
        }
        sqlStat.deleteCharAt(sqlStat.length()-1);

        sqlStat.append(" WHERE USER_RECORD_ID=? AND LOGIN_DATETIME>=? AND LOGIN_DATETIME<=? AND SESSION_ID=?");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        int i=1;
        if(auditLoginOut.getLoginStatus()!=null){
          setPrepareStatement(preStat, i++, auditLoginOut.getLoginStatus());
        }

        if(auditLoginOut.getLogoutDatetime()!=null){
          setPrepareStatement(preStat, i++, auditLoginOut.getLogoutDatetime());
        }

        if(auditLoginOut.getTimeoutFlag()!=null){
          setPrepareStatement(preStat, i++, auditLoginOut.getTimeoutFlag());
        }

        setPrepareStatement(preStat, i++, auditLoginOut.getUserRecordID());
        setPrepareStatement(preStat, i++, Utility.addSecond(auditLoginOut.getLoginDatetime(), -1));
        setPrepareStatement(preStat, i++, auditLoginOut.getLoginDatetime());
        setPrepareStatement(preStat, i++, auditLoginOut.getSessionID());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          return null;//throw new ApplicationException("common.E00005");
        } else {
          return(auditLoginOut);
        }
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException("common.E00011", e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    AuditLoginOut tmpAuditLoginOut = (AuditLoginOut)((AuditLoginOut)obj).clone();
    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM AUDIT_LOGIN_OUT ");
        sqlStat.append("WHERE USER_RECORD_ID=?");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpAuditLoginOut.getID());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException("common.E00005");
        } else {
          return(tmpAuditLoginOut);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException("common.E000012", e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(com.dcivision.framework.web.AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.USER_RECORD_ID, A.LOGIN_DATETIME, A.LOGIN_STATUS, A.LOGOUT_DATETIME, A.TIMEOUT_FLAG, A.IP_ADDRESS, B.LOGIN_NAME, A.SESSION_ID ");
        sqlStat.append("FROM   AUDIT_LOGIN_OUT A, USER_RECORD B ");
        sqlStat.append("WHERE  A.USER_RECORD_ID = B.ID ");
        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 1, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 1, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          AuditLoginOut tmpAuditLoginOut = new AuditLoginOut();
          tmpAuditLoginOut.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
          tmpAuditLoginOut.setLoginDatetime(getResultSetTimestamp(rs, "LOGIN_DATETIME"));
          tmpAuditLoginOut.setLoginStatus(getResultSetString(rs, "LOGIN_STATUS"));
          tmpAuditLoginOut.setLogoutDatetime(getResultSetTimestamp(rs, "LOGOUT_DATETIME"));
          tmpAuditLoginOut.setTimeoutFlag(getResultSetString(rs, "TIMEOUT_FLAG"));
          tmpAuditLoginOut.setIPAddress(getResultSetString(rs, "IP_ADDRESS"));
          tmpAuditLoginOut.setLoginName(getResultSetString(rs, "LOGIN_NAME"));
          tmpAuditLoginOut.setSessionID(getResultSetString(rs, "SESSION_ID"));
          tmpAuditLoginOut.setRecordCount(totalNumOfRecord);
          tmpAuditLoginOut.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpAuditLoginOut);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.USER_RECORD_ID, A.LOGIN_DATETIME, A.LOGIN_STATUS, A.LOGOUT_DATETIME, A.TIMEOUT_FLAG, A.IP_ADDRESS, B.LOGIN_NAME, A.SESSION_ID ");
        sqlStat.append("FROM   AUDIT_LOGIN_OUT A, USER_RECORD B ");
        sqlStat.append("WHERE  A.USER_RECORD_ID = B.ID ");

        // Retrieve the result in row basis.
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = preStat.executeQuery();

        while (rs.next()) {
          AuditLoginOut tmpAuditLoginOut = new AuditLoginOut();
          tmpAuditLoginOut.setUserRecordID(getResultSetInteger(rs, "USER_RECORD_ID"));
          tmpAuditLoginOut.setLoginDatetime(getResultSetTimestamp(rs, "LOGIN_DATETIME"));
          tmpAuditLoginOut.setLoginStatus(getResultSetString(rs, "LOGIN_STATUS"));
          tmpAuditLoginOut.setLogoutDatetime(getResultSetTimestamp(rs, "LOGOUT_DATETIME"));
          tmpAuditLoginOut.setTimeoutFlag(getResultSetString(rs, "TIMEOUT_FLAG"));
          tmpAuditLoginOut.setIPAddress(getResultSetString(rs, "IP_ADDRESS"));
          tmpAuditLoginOut.setLoginName(getResultSetString(rs, "LOGIN_NAME"));
          tmpAuditLoginOut.setSessionID(getResultSetString(rs, "SESSION_ID"));
          result.add(tmpAuditLoginOut);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
  }

  
  public synchronized void resetLoginLog() throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE AUDIT_LOGIN_OUT ");
        sqlStat.append("SET ");
        sqlStat.append("LOGIN_STATUS=?,");
        sqlStat.append("LOGOUT_DATETIME=?,");
        sqlStat.append("TIMEOUT_FLAG=? ");        
        sqlStat.append("WHERE LOGIN_STATUS =? AND (LOGOUT_DATETIME IS NULL OR LOGOUT_DATETIME = '' )");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        int i=1;        
        setPrepareStatement(preStat, i++, AuditLoginOut.STATUS_TIMEOUT);
        setPrepareStatement(preStat, i++, Utility.getCurrentTimestamp());
        setPrepareStatement(preStat, i++, "Y");
        setPrepareStatement(preStat, i++, AuditLoginOut.STATUS_LOGIN_SUCCESS);  
        updateCnt = preStat.executeUpdate();
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException("common.E00011", e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }  
  
  
}